<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-07
 * Time: 17:35
 */

namespace app\admin\model\traits;


use service\TreeService;

trait NavTree
{
    /**
     * 构建ElementNavMenu的树形数据
     * @param array $menu_data
     * @return array
     */
    protected static function buildElementNavMenu(array $menu_data)
    {
        if (!is_array($menu_data)) {
            return [];
        }

        // 对原始数据进行处理
        $menu_data = self::_handleElementNavMenuRawData($menu_data);

        // 对数据进行tree序列化
        return TreeService::listToTree($menu_data, 'id', 'pid', 'children', 0);
    }

    /**
     * 重新处理elementNavMenu的数据
     * @param array $menu_data
     * @return array
     */
    protected static function _handleElementNavMenuRawData(array $menu_data)
    {
        $new_menu_data = [];
        foreach ($menu_data as $key => $value) {
            $new_menu_data[$key]['id'] = $value['id'];
            $new_menu_data[$key]['pid'] = $value['pid'];
            $new_menu_data[$key]['name'] = $value['name'];
            $new_menu_data[$key]['path'] = $value['path'];
            $new_menu_data[$key]['url'] = $value['url'];
            $new_menu_data[$key]['redirect'] = $value['redirect'];
            $new_menu_data[$key]['hidden'] = $value['hidden'] === 1 ? true : false;
            $new_menu_data[$key]['always_show'] = $value['always_show'] === 1 ? true: false;
            $new_menu_data[$key]['meta'] = [
                'title' => $value['title'],
                'icon' => $value['icon'],
                'noCache' => $value['no_cache'] === 1 ? true : false,
                'breadcrumb' => $value['breadcrumb_show'] === 1 ? true : false
            ];
        }

        return $new_menu_data;
    }
}